package cn.zjh.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {

        String token = req.getHeader("token");

        //如果token不为空
        if (token != null){
            //那就获取redis中的用户信息
            Object logininfo = redisTemplate.opsForValue().get(token);
            //如果用户信息也不为空
            if (logininfo != null){
                //重置过期时间，并放行
                redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //如果token为空
        //设置编码
        resp.setCharacterEncoding("UTF-8");
        //设置响应参数类型为JSON
        resp.setContentType("application/json;charset=UTF-8");
        //获取打印流，返回前端错误信息
        PrintWriter writer = resp.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        //刷新关流，并拦截
        writer.flush();
        writer.close();
        return false;
    }
}
